import { defineStore } from 'pinia'
import { authApi, userApi } from '../api'

export const useUserStore = defineStore('user', {
  // 状态
  state: () => ({
    user: null,
    favorites: [],
    loading: false,
    error: null
  }),
  
  // getters
  getters: {
    isAuthenticated: (state) => !!state.user,
    username: (state) => state.user?.username || '游客',
    userId: (state) => state.user?.id
  },
  
  // actions
  actions: {
    // 设置用户信息
    setUser(userData) {
      this.user = userData
      if (userData) {
        localStorage.setItem('weatherAppUser', JSON.stringify(userData))
      } else {
        localStorage.removeItem('weatherAppUser')
      }
    },
    
    // 初始化用户信息（从本地存储中获取）
    initUser() {
      const userData = localStorage.getItem('weatherAppUser')
      if (userData) {
        try {
          const parsedData = JSON.parse(userData)
          this.user = parsedData
          
          // 初始化后尝试获取用户信息以验证会话
          this.validateSession()
        } catch (error) {
          console.error('解析用户数据失败:', error)
          localStorage.removeItem('weatherAppUser')
          this.user = null
        }
      }
    },
    
    // 验证会话是否有效
    async validateSession() {
      try {
        // 尝试获取收藏列表，如果成功则说明会话有效
        await this.fetchFavorites()
      } catch (error) {
        console.error('会话验证失败:', error)
        if (error.response && error.response.status === 401) {
          console.log('会话已过期，清除用户状态')
          this.setUser(null)
        }
      }
    },
    
    // 注册
    async register(userData) {
      this.loading = true
      this.error = null
      try {
        const response = await authApi.register(userData)
        this.setUser(response.data.user)
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 登录
    async login(credentials) {
      this.loading = true
      this.error = null
      try {
        const response = await authApi.login(credentials)
        this.setUser(response.data.user)
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 登出
    async logout() {
      this.loading = true
      this.error = null
      try {
        await authApi.logout()
        this.setUser(null)
        this.favorites = []
      } catch (error) {
        this.error = error.response?.data?.message || '登出失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      if (!this.isAuthenticated) return
      
      this.loading = true
      this.error = null
      try {
        const response = await userApi.getCurrentUser()
        this.setUser(response.data.user)
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户信息失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新用户信息
    async updateUser(userData) {
      if (!this.isAuthenticated) return
      
      this.loading = true
      this.error = null
      try {
        const response = await userApi.updateUser(userData)
        this.setUser(response.data.user)
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '更新用户信息失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取收藏城市列表
    async fetchFavorites() {
      if (!this.isAuthenticated) {
        this.favorites = [];
        return;
      }
      
      this.loading = true;
      this.error = null;
      try {
        const response = await userApi.getFavorites();
        this.favorites = response.data.favorites;
        return response;
      } catch (error) {
        // 如果是401未授权错误，静默处理并设置空收藏列表
        if (error.response && error.response.status === 401) {
          this.favorites = [];
          // 可能是token过期，清除用户信息
          this.setUser(null);
        } else {
          this.error = error.response?.data?.message || '获取收藏城市失败';
          throw error;
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 添加收藏城市
    async addFavorite(city, province) {
      if (!this.isAuthenticated) return
      
      this.loading = true
      this.error = null
      try {
        const response = await userApi.addFavorite(city, province)
        await this.fetchFavorites() // 刷新收藏列表
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '添加收藏城市失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 移除收藏城市
    async removeFavorite(city, province) {
      if (!this.isAuthenticated) return
      
      this.loading = true
      this.error = null
      try {
        const response = await userApi.removeFavorite(city, province)
        await this.fetchFavorites() // 刷新收藏列表
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '移除收藏城市失败'
        throw error
      } finally {
        this.loading = false
      }
    }
  }
}) 